package li.buda.blueprint.blazeds.client.facade {
import mx.controls.Alert;
import mx.rpc.AbstractOperation;
import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;
import mx.rpc.remoting.RemoteObject;

public class RemoteInvoker {
    private var ro:RemoteObject;

    public function RemoteInvoker(ro:RemoteObject) {
        this.ro = ro;
    }

    public function invoke(method:String, params:Array, onResult:Function, onFault:Function):void {
        var op:AbstractOperation = ro.getOperation(method);
        var onResultCallback:Function = function(event:ResultEvent):void {
            op.removeEventListener(ResultEvent.RESULT, onResultCallback);
            op.removeEventListener(FaultEvent.FAULT, onFaultCallback);
        };
        var onFaultCallback:Function = function(event:FaultEvent):void {
            op.removeEventListener(ResultEvent.RESULT, onResultCallback);
            op.removeEventListener(FaultEvent.FAULT, onFaultCallback);
            //TODO: Would be nice to have some default error preprocessing so that for example missing method error would get caught and some less generic error could be thrown
            if (onFault != null) {
                onFault(event.fault);
            } else {
                defaultOnFault(event.fault);
            }
        };
        op.addEventListener(ResultEvent.RESULT, onResultCallback);
        op.addEventListener(FaultEvent.FAULT, onFaultCallback);
        op.arguments = params;
        op.send();
    }

    private function defaultOnFault(error:Error):void {
        Alert.show(error.message);
    }
}
}